//
//  main.cpp
//  DayTimeServer2
//
//  Created by Ge Jian Feng on 14-5-25.
//  Copyright (c) 2014年 Ge Jian Feng. All rights reserved.
//

#include <iostream>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <time.h>

#define MAXLINE                     4096
#define bzero(addr, len)            memset(addr, 0, len)

int main(int argc, const char * argv[])
{
    // Initialize variable
    int                             socketId, connectId;
    struct sockaddr_in6             servaddr;
    char                            buff[MAXLINE];
    time_t                          ticks;
    int                             status;
    
    // Create socket
    socketId = socket(AF_INET6, SOCK_STREAM, 0);
    if (socketId < 0) {
        std::cerr << "Create socket error!" << std::endl;
        exit(1);
    }
    
    // Initialize IP address
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin6_family = AF_INET6;
    servaddr.sin6_port = htons(13000);
    servaddr.sin6_len = sizeof(servaddr);
    if (inet_pton(AF_INET6, "::1", &servaddr.sin6_addr) <= 0) {
        std::cerr << "inet_pton error for ::1" << std::endl;
        exit(1);
    }
    
    // Bind socket
    status = bind(socketId, (struct sockaddr*)&servaddr, sizeof(servaddr));
    if (status < 0) {
        std::cerr << "Fail to bind socket!" << std::endl;
        exit(1);
    }
    
    // Listen socket
    if (listen(socketId, 1024)) {
        std::cerr << "Listen error!" << std::endl;
        exit(1);
    }
    
    // Process logic
    for (;;) {
        connectId = accept(socketId, (struct sockaddr*)NULL, NULL);
        ticks = time(NULL);
        snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
        write(connectId, buff, strlen(buff));
        close(connectId);
    }
    
    return 0;
}

